package course.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import course.pojo.entity.*;
import course.pojo.vo.Page;
import course.pojo.vo.StudentRespVo;
import course.service.*;
import course.service.impl.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author HLF
 * @date 2022/7/2 20:05
 */
@WebServlet("/student/studentOwnController")
public class StudentOwnController extends BaseController {
    private StudentService studentService = new StudentServiceImpl();
    private SubjectService subjectService = new SubjectServiceImpl();
    private StuSubService stuSubService = new StuSubServiceImpl();
    private ZhuanyeService zhuanyeService = new ZhuanyeServiceImpl();
    private StuTeaService stuTeaService = new StuTeaServiceImpl();

    private CollegeService collegeService = new CollegeServiceImpl();


    /**
     * 跳转到学生选课页面
     * 页面需要的数据：所有课程信息，当前学生已经选择的课程信息
     */
    protected void stuCourse(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String opn = req.getParameter("opn");
        String apn = req.getParameter("apn");
        if (StringUtils.isBlank(opn) || Integer.parseInt(opn) <= 0) {
            opn = "1";
        }
        if (StringUtils.isBlank(apn) || Integer.parseInt(apn) <= 0) {
            apn = "1";
        }
        this.index(req, resp, opn, apn);
    }

    /**
     * 查询当前student对应的学院的所有课程
     */
    protected void index(HttpServletRequest req, HttpServletResponse resp, String opn, String apn) throws ServletException, IOException {
        HttpSession session = req.getSession();
        //获取当前登录的student对象
        Student student = (Student) session.getAttribute("sstudent");
        Integer zid = student.getZid();
        Zhuanye zhuanye = zhuanyeService.getById(zid);
        Integer cid = zhuanye.getCid();

        //获取当前student已经选择的课程，并进行分页
        Page<Subject> ownSubjectPage = subjectService.ownPage2(Integer.valueOf(opn), student.getSid());

        //获取所有课程信息,并进行分页
        Page<Subject> allSubjectPage = subjectService.page2(Integer.valueOf(apn), cid);

        req.setAttribute("ownSubjectPage", ownSubjectPage);
        req.setAttribute("allSubjectPage", allSubjectPage);

        req.getRequestDispatcher("/stusub_manage.jsp").forward(req, resp);
    }

    /**
     * 学生选课
     */
    protected void order(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        int i = 0;

        HttpSession session = req.getSession();
        Student student = (Student) session.getAttribute("sstudent");
        Integer sid = student.getSid();
        String suid = req.getParameter("suid");
        StuSub stuSub = stuSubService.getBySidAndSuid(sid, Integer.valueOf(suid));

        if (stuSub == null) {
            i = stuSubService.addStuSub(new StuSub(sid, Integer.valueOf(suid)));
        }

        writer.println(i);
        writer.flush();
    }

    /**
     * 退课
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Student student = (Student) session.getAttribute("sstudent");
        Integer sid = student.getSid();
        String suid = req.getParameter("suid");

        int i = stuSubService.deleteBySidAndSuid(sid, Integer.valueOf(suid));

        //退完课之后需要把选择过的老师也退掉
        List<StuTea> bySidSuid = stuTeaService.getBySidSuid(sid, Integer.valueOf(suid));
        bySidSuid.forEach(stuTea -> {
            stuTeaService.deleteBySidTidSuid(sid, stuTea.getTid(), Integer.valueOf(suid));
        });

        if (i > 0) {
            this.stuCourse(req, resp);
        }
    }

    /**
     * 批量退课
     */
    protected void deleteSelect(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] ids = req.getParameterValues("ids[]");

        HttpSession session = req.getSession();
        Student student = (Student) session.getAttribute("sstudent");
        Integer sid = student.getSid();

        List<String> strings = Arrays.asList(ids);

        //所有要退的课的suid
        List<Integer> integers = strings.stream().map(Integer::valueOf).collect(Collectors.toList());
        int i = stuSubService.deleteSelect(integers, sid);

        //退完课之后需要把选择过的教师也退掉
        integers.forEach(suid -> {
            List<StuTea> bySidSuid = stuTeaService.getBySidSuid(sid, suid);
            bySidSuid.forEach(stuTea -> {
                stuTeaService.deleteBySidTidSuid(sid, stuTea.getTid(), suid);
            });
        });
    }

    /**
     * 跳转到学生个人中心
     */
    protected void centerPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Student student = (Student) session.getAttribute("sstudent");

        StudentRespVo studentRespVo = new StudentRespVo();
        try {
            BeanUtils.copyProperties(studentRespVo, student);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //设置zname，cid，cname
        Zhuanye zhuanye = zhuanyeService.getById(student.getZid());
        studentRespVo.setZname(zhuanye.getZname());
        studentRespVo.setCid(zhuanye.getCid());
        studentRespVo.setCname(collegeService.getById(zhuanye.getCid()).getCname());

        req.setAttribute("studentVo", studentRespVo);
        req.getRequestDispatcher("/student_center.jsp").forward(req, resp);
    }

    /**
     * 修改基本信息
     */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sid = req.getParameter("sid");
        String ssex = req.getParameter("ssex");
        String spassword2 = req.getParameter("spassword2");//新密码

        HttpSession session = req.getSession();
        Student student = (Student) session.getAttribute("sstudent");

        if (StringUtils.isNotBlank(ssex)) {
            student.setSsex(ssex);
        }
        if (StringUtils.isNotBlank(spassword2)) {
            String pass = DigestUtil.bcrypt(spassword2);
            student.setSpassword(pass);
        }

        student.setSid(Integer.valueOf(sid));

        //修改基本信息
        int i = studentService.updateInfo(student);

        session.setAttribute("sstudent", student);
        this.centerPage(req, resp);
    }


    /**
     * 验证密码：
     * 1.原密码或新密码为空
     * 2.原密码错误
     * 3.两次密码不一致
     */
    protected void pass(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();

        String spassword = req.getParameter("spassword");
        String spassword2 = req.getParameter("spassword2");
        String spassword3 = req.getParameter("spassword3");

        Map<String, Object> result = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();

        if (StringUtils.isBlank(spassword) || StringUtils.isBlank(spassword2) || StringUtils.isBlank(spassword3)) {
            result.put("code", 0);
            result.put("msg", "原密码或新密码不能为空");
            String s = mapper.writeValueAsString(result);
            writer.println(s);
            return;
        }

        if (!spassword2.equalsIgnoreCase(spassword3)) {
            result.put("code", 0);
            result.put("msg", "两次密码不一致！");
            String s = mapper.writeValueAsString(result);
            writer.println(s);
            return;
        }

        HttpSession session = req.getSession();
        Student student = (Student) session.getAttribute("sstudent");
        boolean check = DigestUtil.bcryptCheck(spassword, student.getSpassword());
        if (!check) {
            result.put("code", 0);
            result.put("msg", "原密码错误！");
            String s = mapper.writeValueAsString(result);
            writer.println(s);
        }
    }
}
